package cn.wsn2018.tools.listener;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.ctrl.UserController;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.model.SystemConfig;
import cn.wsn2018.tools.service.SecUserService;
import cn.wsn2018.tools.util.StorageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Created by NZX on 2018/12/18.
 */
@WebListener
public class SessionListener implements HttpSessionListener{
    private MySessionContext myc = MySessionContext.getInstance();
    private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);

    @Autowired
    private SecUserService secUserService;

    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        //获取系统配置
        SystemConfig config=null;

        //为啥用while？启动的时候需要时间，但是如果在启动过程中，用户发起了请求，会报java.lang.NullPointerException: null
        //后期还可以设置最大时间
        while (config==null){
            config=secUserService.getStorageSystemConfig();
        }
        //根据系统管理员配置来设置会话超时时间
        Integer sessionOutOfTime=Integer.parseInt(config.getSessionMaxOverTime());
        //设置超时时间
        CommonValue.SESSION_OUT_OF_TIME=sessionOutOfTime*60;
        logger.info("SessionMaxOverTime："+CommonValue.SESSION_OUT_OF_TIME+",config Time:"+sessionOutOfTime);
        session.setMaxInactiveInterval(CommonValue.SESSION_OUT_OF_TIME);
        myc.addSession(session);//记录了所有已经登录用户信息
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        String sessionId = session.getId();
        //将列表里的对应的session移除
        StorageUtil.getInstance().removeSessions(sessionId);
        myc.delSession(session);
    }
}
